<template>
  <view class="container">
    <!-- 返回按钮 -->
    <BackButton />
    
    <!-- 加载中状态 -->
    <view v-if="loading" class="loading-container">
      <text>正在加载考试结果...</text>
    </view>
    
    <!-- 考试结果详情 -->
    <view v-else-if="examResult" class="result-container">
      <!-- 总分显示 -->
      <view class="score-section">
        <view class="total-score">
          <text class="score-label">总分</text>
          <text class="score-value">{{ examResult.averageScore }}/100</text>
        </view>
        <view class="score-details">
          <text>答题数：{{ examResult.validQuestions }}/{{ examResult.totalQuestions }}</text>
        </view>
      </view>
      
      <!-- 考试信息 -->
      <view class="exam-info-section">
        <h3>考试信息</h3>
        <view class="info-item">
          <text class="info-label">考试时间：</text>
          <text class="info-value">{{ formatDateTime(examResult.actualStartTime) }} - {{ formatDateTime(examResult.actualEndTime) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">考试状态：</text>
          <text class="info-value" :class="getStatusClass(examResult.status)">{{ getStatusText(examResult.status) }}</text>
        </view>
      </view>
      
      <!-- 题目详情 -->
      <view class="questions-section">
        <h3>题目详情</h3>
        <view v-for="(question, index) in examResult.questionResults" :key="question.questionId" class="question-item">
          <view class="question-header">
            <text class="question-number">第{{ index + 1 }}题</text>
            <text class="question-score">{{ question.score }}分</text>
          </view>
          <view class="question-content">
            <text class="question-text">{{ question.questionText }}</text>
          </view>
          <view v-if="question.answerText" class="user-answer">
            <text class="answer-label">您的回答：</text>
            <text class="answer-text">{{ question.answerText }}</text>
          </view>
          <view v-if="question.modelAnswer" class="model-answer">
            <text class="answer-label">评分原因：</text>
            <text class="answer-text">{{ question.modelAnswer }}</text>
          </view>
        </view>
      </view>
      
      <!-- 铭牌信息 -->
      <view v-if="examResult.badgeInfo && examResult.badgeInfo.length > 0" class="badges-section">
        <h3>相关铭牌</h3>
        <view v-for="badge in examResult.badgeInfo" :key="badge.id" class="badge-item" @click="goToTaskDetail(badge.taskId)">
          <view class="badge-header">
            <text class="badge-name">{{ badge.association }}</text>
            <text class="badge-level">Lv.{{ badge.level }}</text>
          </view>
          <view v-if="badge.evaluation" class="badge-evaluation">
            <text>{{ badge.evaluation }}</text>
          </view>
          <view v-if="badge.contributorScore !== undefined" class="badge-score">
            <text>贡献分数：{{ badge.contributorScore }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 错误状态 -->
    <view v-else class="error-container">
      <text class="error-text">加载考试结果失败</text>
      <button @click="loadExamResult" class="retry-btn">重试</button>
    </view>
  </view>
</template>

<script>
import BackButton from '@/components/BackButton.vue'

export default {
  components: {
    BackButton
  },
  
  data() {
    return {
      examTaskId: null,
      examResult: null,
      loading: true
    }
  },
  
  methods: {
    // 初始化页面
    async initPage() {
      try {
        // 从URL获取参数
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const options = currentPage.options;
        const examTaskId = options.examTaskId;
        
        console.log('获取到的examTaskId:', examTaskId);
        
        if (!examTaskId) {
          this.showToast('缺少考试任务ID');
          return;
        }
        
        this.examTaskId = examTaskId;
        
        // 加载考试结果
        await this.loadExamResult();
      } catch (error) {
        console.error('初始化页面失败:', error);
        this.showToast('页面初始化失败');
      }
    },
    
    // 加载考试结果
    async loadExamResult() {
      if (!this.examTaskId) {
        console.warn('[DEBUG] 没有examTaskId，无法获取考试结果');
        return;
      }
      
      try {
        this.loading = true;
        console.log('[DEBUG] 开始获取考试结果，examTaskId:', this.examTaskId);
        
        const response = await uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/exam/result?examTaskId=${this.examTaskId}`,
          method: 'GET',
          header: {
            'Access-Token': `Bearer ${uni.getStorageSync('accessToken')}`
          }
        });
        
        if (response.statusCode === 200 && response.data && response.data.success) {
          this.examResult = response.data.result;
          console.log('[DEBUG] 考试结果获取成功:', this.examResult);
        } else {
          console.error('[DEBUG] 获取考试结果失败:', response.data);
          this.showToast('获取考试结果失败');
        }
      } catch (error) {
        console.error('[DEBUG] 获取考试结果异常:', error);
        this.showToast('获取考试结果失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    
    // 跳转到任务详情页
    goToTaskDetail(taskId) {
      if (!taskId) {
        this.showToast('任务ID不存在');
        return;
      }
      
      console.log('[DEBUG] 跳转到任务详情页，taskId:', taskId);
      uni.navigateTo({
        url: `/pages/task/detail/index?taskId=${taskId}`
      });
    },
    
    // 格式化日期时间
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '未知';
      
      try {
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        return dateTimeStr;
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 0: return '待预约';
        case 1: return '已预约';
        case 2: return '进行中';
        case 3: return '已完成';
        case 4: return '异常结束';
        default: return '未知状态';
      }
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case 3: return 'status-completed';
        case 4: return 'status-abnormal';
        default: return 'status-default';
      }
    },
    
    // 显示提示
    showToast(message) {
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 3000
      });
    }
  },
  
  mounted() {
    this.initPage();
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.loading-container {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.result-container {
  width: 100%;
  max-width: 800px;
}

.score-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  border-radius: 16px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.total-score {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
}

.score-label {
  font-size: 18px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.score-value {
  font-size: 48px;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.score-details {
  font-size: 16px;
  opacity: 0.8;
}

.exam-info-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.exam-info-section h3 {
  color: #333;
  margin-bottom: 15px;
  font-size: 18px;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 80px;
}

.info-value {
  color: #333;
  flex: 1;
}

.status-completed {
  color: #28a745;
  font-weight: bold;
}

.status-abnormal {
  color: #dc3545;
  font-weight: bold;
}

.status-default {
  color: #666;
}

.questions-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.questions-section h3 {
  color: #333;
  margin-bottom: 15px;
  font-size: 18px;
}

.question-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  border-left: 4px solid #007aff;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.question-number {
  font-weight: bold;
  color: #333;
}

.question-score {
  background: #007aff;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: bold;
}

.question-content {
  margin-bottom: 10px;
}

.question-text {
  color: #666;
  line-height: 1.5;
}

.user-answer {
  background: #e3f2fd;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 10px;
  border-left: 3px solid #2196f3;
}

.model-answer {
  background: #f1f8e9;
  padding: 10px;
  border-radius: 6px;
  border-left: 3px solid #28a745;
}

.answer-label {
  font-weight: bold;
  margin-right: 5px;
}

.user-answer .answer-label {
  color: #2196f3;
}

.model-answer .answer-label {
  color: #28a745;
}

.answer-text {
  color: #555;
  line-height: 1.4;
}

.badges-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.badges-section h3 {
  color: #333;
  margin-bottom: 15px;
  font-size: 18px;
}

.badge-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 12px;
  border: 2px solid #e9ecef;
  cursor: pointer;
  transition: all 0.3s ease;
}

.badge-item:hover {
  border-color: #007aff;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
}

.badge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.badge-name {
  font-weight: bold;
  color: #333;
  font-size: 16px;
}

.badge-level {
  background: #ffc107;
  color: #333;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: bold;
}

.badge-evaluation {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.badge-score {
  color: #007aff;
  font-size: 14px;
  font-weight: bold;
}

.error-container {
  text-align: center;
  padding: 40px 20px;
}

.error-text {
  color: #dc3545;
  font-size: 18px;
  font-weight: bold;
  display: block;
  margin-bottom: 20px;
}

.retry-btn {
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
}
</style>
